<?php

namespace app\health\controller;

use app\health\model\tracking\HealthTrackingHealth;
use app\health\model\tracking\HealthTrackingMonitorDuration;
use think\Db;

class Tracking extends ApiBase
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['click', 'page_duration'];

    /**
     * 事件ID
     * @Author 张旭鹏
     * @DateTime 2023-06-30
     */
    protected $eventId = 0;

    protected function _initialize()
    {
        parent::_initialize();
        $eventCode = $this->request->param('event_code', '');
        if ($eventCode) {
            $this->eventId = Db::name('health_tracking_event')->where('event_code', $eventCode)->cache(86400)->value('id') ?: 0;
        }
    }

    /**
     * 记录点击事件
     * @Author 张旭鹏
     * @DateTime 2023-06-30
     */
    public function click()
    {
        $eventCode = $this->request->param('event_code', '');
        if (!empty($eventCode)) {
            Db::name('health_tracking_monitor')->insert([
                'event_id'    => $this->eventId,
                'user_id'     => $this->auth->id ?: 0,
                'ip'          => $this->request->ip(),
                'create_time' => time(),
                'event_code'  => $eventCode
            ]);
        }
        $this->success('记录成功');
    }

    /**
     * 健康服务点击事件记录
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public function health(): void
    {
        $event  = $this->request->param('event');
        $row_id = $this->request->param('row_id', 0);
        $row    = null;
        if ($row_id) {
            $row = HealthTrackingHealth::where('id', $row_id)->find();
        }
        if ($row) {
            $row->save([
                'is_use' => $this->request->param('is_use', 0),
            ]);
        } else {
            $row = HealthTrackingHealth::create([
                'type'        => $event,
                'source_page' => $this->request->param('page', ''),
                'user_id'     => $this->auth->id ?: 0,
                'ip'          => $this->request->ip()
            ]);
        }
        $row_id = $row->id;
        $this->success('success', compact('row_id'));
    }

    /**
     * 记录页面停留时长
     * @return void
     */
    public function page_duration(): void
    {
        $page = $this->request->param('page', '');
        if ($page) {
            HealthTrackingMonitorDuration::create([
                'page'        => $page,
                'duration'    => $this->request->param('duration/d', 0),
                'user_id'     => $this->auth->id ?: 0,
                'ip'          => $this->request->ip(),
                'create_time' => time()
            ]);
        }
        $this->success('success');
    }
}
